package com.djhu.freepartner.web.service.session;

import com.djhu.freepartner.bean.PartnerUser;
import com.djhu.freepartner.core.constant.Global;
import com.djhu.freepartner.utils.DateUtils;
import com.google.common.base.Joiner;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class SessionServiceImpl implements ISessionService{

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 幂等性 一个用户生成的sessionid必须一致
     * @param partnerUser
     * @return
     */
    @Override
    public String createSessionId(PartnerUser partnerUser) {
        String userId = partnerUser.getUserid();
        return Joiner.on("_").join(Global.SESSION_USER,userId, DateUtils.now());
    }

    @Override
    public PartnerUser selectUserBySessionId(String sessionId) {
        String str = String.valueOf(redisTemplate.opsForValue().get(sessionId));
        if (StringUtils.isEmpty(str)){
            return null;
        }
        PartnerUser partnerUser = (PartnerUser) JSONObject.toBean(JSONObject.fromObject(str),PartnerUser.class);
        return partnerUser;
    }

    @Override
    public PartnerUser addPartnerUserToSession(PartnerUser partnerUser) {
        String sessionId = createSessionId(partnerUser);

        //查找之前的sessionid 并且删除
        deleteSession(partnerUser);
//        String oldSessionID = (String) redisTemplate.opsForValue().get(partnerUser.getUserid());
//        redisTemplate.delete(partnerUser.getUserid());
//        if (StringUtils.isNotEmpty(oldSessionID)) {
//            redisTemplate.delete(oldSessionID);
//        }
        String str = JSONObject.fromObject(partnerUser).toString();
        redisTemplate.opsForValue().set(partnerUser.getUserid(),sessionId);
        redisTemplate.opsForValue().set(sessionId,str);
        partnerUser.setSessionid(sessionId);
        return partnerUser;
    }

    @Override
    public void deleteSession(PartnerUser partnerUser) {
        //查找之前的sessionid 并且删除
        String oldSessionID = String.valueOf(redisTemplate.opsForValue().get(partnerUser.getUserid()));
        redisTemplate.delete(partnerUser.getUserid());
        if (StringUtils.isNotEmpty(oldSessionID)) {
            redisTemplate.delete(oldSessionID);
        }
    }
}
